﻿package com.petermacko.utils {
	import flash.utils.Dictionary;		

	/**
	 * The Singleton class is a helper class to enforce singletons and enables subclassing of singletons.
	 * 
	 * @example How singletons are implemented:
	 * public class Model
	 * {
	 *     private static var inst:Model;
	 *     public function Model()
	 *     {
	 *         Singleton.assertSingle(Model);
	 *     }
	 *     public static function gi():Model
	 *     {
	 *         if(!inst) inst = Singleton.gi(Model);
	 *         return inst;
	 *     }
	 * }
	 */
	final public class Singleton
	{
		private static var insts:Dictionary; //Keeps track of the instances available.
		
		public static function gi(clazz:Class,...cancelParentClasses:Array):* {
			var inst:*;
			if(!insts) insts = new Dictionary();
			if(insts[clazz] && insts[clazz] != -1) inst = insts[clazz];
			if(!inst) {
				inst = new clazz();
				insts[clazz] = inst;
			}
			if(cancelParentClasses) for each(var cl:Class in cancelParentClasses){insts[cl] = -1;}
			return inst;
		}
		//Assert that there is only one instance of a class.
		public static function assertSingle(clazz:Class):void {
			if(insts[clazz]) throw new Error("Error creating class, {"+clazz+"}. It's a singleton and cannot be instantiated more than once.");
		}
	}
}